<template>
  <div class="w-full" v-loading="loading">
    <el-table :data="list" v-loading="loading" row-class-name="cursor-pointer" @row-click="openDrawer">
      <el-table-column
        label="工单编号"
        prop="workOrderNumber"
        width="220"
      ></el-table-column>
      <el-table-column
        label="联系人"
        prop="contactUser"
        width="110"
      ></el-table-column>
      <el-table-column
        label="联系方式"
        prop="contactUserMobile"
        width="120"
      ></el-table-column>
      <el-table-column
        label="邮箱"
        prop="contactUserEmail"
        width="140"
      ></el-table-column>
      <el-table-column
        label="问题描述"
        prop="workOrderDesc"
        show-overflow-tooltip
      ></el-table-column>
      <el-table-column
        label="问题类型"
        width="140"
        prop="workOrderTitle"
      ></el-table-column>
      <el-table-column label="工单状态" width="140">
        <template #default="{ row }">{{
          ORDER_STATUS[row.workOrderStatus]
        }}</template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        prop="createTime"
        width="200"
      ></el-table-column>
      <el-table-column
        label="结单人"
        width="140"
        prop="overUserName"
      ></el-table-column>
      <el-table-column
        label="备注"
        show-overflow-tooltip
        width="160"
        prop="remark"
      ></el-table-column>
    </el-table>
    <el-pagination
      v-show="list.length"
      class="w-full justify-end mt-12px"
      :total="total"
      layout="total, sizes, prev, pager, next"
      v-model:current-page="page.pageNum"
      v-model:page-size="page.pageSize"
      :page-sizes="[10, 30, 60, 120]"
    ></el-pagination>
    <el-drawer
      v-model="drawerVisible"
      :title="drawerTitle"
      destroy-on-close
      class="msg-drawer"
      size="50%"
      :before-close="beforeDrawerClose"
    >
      <div class="msg-wrap w-full px-20px" ref="inner">
        <div
          v-for="msg in msgList"
          :key="msg.time"
          class="mb-12px"
          :class="{ 'text-right': msgInRight(msg) }"
        >
          <div class="font-size-14px text-light mb-2px">
            {{ msgInRight(msg) ? "我 |" : `${msg.createBy} |` }}
            {{ msg.createTime }}
          </div>
          <div class="msg-pop">{{ msg.msgContent }}</div>
        </div>
        <div v-if="!msgList.length" class="text-center text-light">
          暂无消息
        </div>
      </div>
      <template #footer>
        <div class="chat-box-input p-16px" v-if="[0, 1].includes(orderStatus)">
          <el-input
            autofocus
            type="textarea"
            class="chat-input"
            resize="none"
            v-model="inputMsg"
          ></el-input>
          <div class="text-right">
            <el-button
              type="primary"
              class="w-64px h-32px b-rd-2px mt-8px"
              @click="handleSend"
              >发送</el-button
            >
          </div>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup>
import { useLoading, usePage } from "@/hooks";
import { useUserStore } from "@/store";
import { ORDER_STATUS } from "@/const";
import { toggleHtmlScroll } from "@/utils/dom";

const { loading, setLoading } = useLoading();
const $api = inject("$api");
const userStore = useUserStore();

const list = ref([]);
const { page, total } = usePage();
const getList = async () => {
  setLoading(true);
  try {
    const { data, total: resTotal } = await $api.order.getOrderList({
      ...page.value,
      companyId: userStore?.userInfo?.companyId,
    });

    list.value = data;
    total.value = resTotal;
  } finally {
    setLoading(false);
  }
};
watch(
  () => page.value,
  () => {
    getList();
  },
  {
    deep: true,
    immediate: true,
  }
);

const workOrderId = ref(""); // 工单id
const orderCreateUserId = ref(""); // 工单创建人id
const orderStatus = ref(null); // 工单status
const drawerVisible = ref(false);
const drawerTitle = ref("");
const msgList = ref([]);
const inputMsg = ref("");
const timer = ref(null);
const inner = ref();
const msgInRight = computed(() => {
  return (msg) => {
    if (msg.createUserId !== userStore.userInfo.userId) return false;
    return (
      (msg.msgType === 0 &&
        userStore.userInfo.userId === orderCreateUserId.value) ||
      (msg.msgType === 1 &&
        userStore.userInfo.userId !== orderCreateUserId.value)
    );
  };
});

const getMsgList = async () => {
  const lastMsg = msgList.value[msgList.value.length - 1];
  const { data } = await $api.order.getOrderMsgList({
    workOrderId: workOrderId.value,
    orderNum: lastMsg ? lastMsg.orderNum : null,
  });
  if (!data?.length) return;
  msgList.value.push(...data);
  scrollToEnd();
};
const openDrawer = (row) => {
  toggleHtmlScroll();
  workOrderId.value = row.id;
  orderCreateUserId.value = row.createUserId;
  orderStatus.value = row.workOrderStatus;
  drawerTitle.value = row.workOrderNumber;
  drawerVisible.value = true;
  timer.value = setInterval((() => (getMsgList(), getMsgList))(), 5000);
};
const handleSend = async () => {
  if (!inputMsg.value) return;
  const { data } = await $api.order.orderSendMsg({
    msgContent: inputMsg.value,
    workOrderId: workOrderId.value,
  });
  msgList.value.push(data);
  scrollToEnd();
  inputMsg.value = "";
};

const scrollToEnd = () => {
  nextTick(() => {
    inner.value.scrollTo({
      top: inner.value.scrollHeight,
    });
  });
};
const beforeDrawerClose = (done) => {
  toggleHtmlScroll();
  clearInterval(timer.value);
  timer.value = null;
  msgList.value = [];
  inputMsg.value = "";
  done();
};
</script>

<style scoped lang="less">
.msg-wrap {
  height: 100%;
  overflow-y: auto;
}
.chat-box-input {
  box-sizing: border-box;
  border-top: 1px solid #d8d8d8;
}
.msg-pop {
  display: inline-block;
  box-sizing: border-box;
  background: #eff2fc;
  border-top-right-radius: 4px;
  border-bottom-left-radius: 4px;
  padding: 10px 16px 13px;
  text-align: left;
  max-width: 80%;
  word-break: break-all;
}
</style>
